import calendar
import csv
import re

import demjson
import requests

headers = {
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36\
         (KHML, like Gecko) Chrome/52.0.2743.116 Safari/537.36',
}


def get_url(date):
    url = 'https://www.timeanddate.com/scripts/cityajax.php?n=china/shenzhen&mode=historic'
    url += '&hd=' + date
    url += '&month=' + str(int(date[4:6]))
    url += '&year=' + date[:4] + '&json=1'

    return url


# input: type(str) eg:'20170601'
def crawl_single_day(date):
    response = requests.get(get_url(date), headers=headers)
    response_list = demjson.decode(response.text)

    for weather in response_list:
        w_time = re.compile(r'^\d+:\d+').search(weather['c'][0]['h']).group(0)
        w_temperature = re.compile(
            r'^-?\d+').search(weather['c'][2]['h']).group(0)
        w_weather = re.compile(
            r'^(.*?)\.').search(weather['c'][3]['h']).group(1)

        if weather['c'][4]['h'] == 'No wind':
            w_wind_speed = '0'
        else:
            w_wind_speed = re.compile(
                r'^\d+').search(weather['c'][4]['h']).group(0)

        w_wind_direction = re.compile(
            r'title=\"(.*?)\"').search(weather['c'][5]['h']).group(1)
        w_humidity = weather['c'][6]['h']
        w_barometer = re.compile(r'^\d+').search(weather['c'][7]['h']).group(0)
        w_visibility = weather['c'][8]['h']
        if w_visibility != 'N/A':
            w_visibility = re.compile(r'^\d+').search(w_visibility).group(0)

        yield [date, w_time, w_temperature, w_weather, w_wind_speed, w_wind_direction,
               w_humidity, w_barometer, w_visibility]


# input: type(int) eg: year=2017, month=6
def crawl_single_month(year, month):
    _, num_day = calendar.monthrange(year, month)
    month_str = str(year)

    if month < 10:
        month_str += '0' + str(month)
    else:
        month_str += str(month)

    day_list = list(range(1, num_day + 1))
    for day in day_list:
        if day < 10:
            for weather in crawl_single_day(month_str + '0' + str(day)):
                yield weather
        else:
            for weather in crawl_single_day(month_str + str(day)):
                yield weather


if __name__ == "__main__":
    with open('weather0.csv', 'w', encoding='utf-8', newline='') as file:
        writer = csv.writer(file)
        writer.writerow('date time temperature weather wind_speed wind_direction humidity barometer visibility'.split())

        for month in range(1, 13):
            writer.writerows(crawl_single_month(2021, month))

    with open('weather1.csv', 'w', encoding='utf-8', newline='') as file:
        writer = csv.writer(file)
        writer.writerow('date time temperature weather wind_speed wind_direction humidity barometer visibility'.split())
        writer.writerows(crawl_single_day('20210401'))
